package org.jaaksi.kottlindemo.flow

import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import extension.stringPref
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import libcore.util.ToastUtil
import org.jaaksi.kottlindemo.databinding.ActivityTestFlowBinding
import org.jetbrains.anko.toast

/**
 * StateFlow 必须设置初始值，如果发射的数据相同只会响应一次
 *
 * ShareFlow
 * 1.replay表示当新的订阅者Collect时，发送几个已经发送过的数据给它，默认为0，即默认新订阅者不会获取以前的数据
 * 2.extraBufferCapacity表示减去replay，MutableSharedFlow还缓存多少数据，默认为0
 * 3.onBufferOverflow表示缓存策略，即缓冲区满了之后Flow如何处理，默认为挂起
 */
class TestLiveDataActivity : AppCompatActivity() {
    private val viewModel by viewModels<TestFlowViewModel>()
    private val aa: String by stringPref(10)
    private val binding by lazy { ActivityTestFlowBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        lifecycleScope.launch {
            viewModel.shareFlow.collect {
                println(">> shareFlow $it")
            }

            // flow在collect之后，协程就关闭了，这段代码不会被执行
            println(">> end")
        }

//        lifecycleScope.launch{
//            // 如果发射的数据不变，stateFlow不会回调collect方法，但livedata会进行回调
//            viewModel.stateFlow.collect {
//                println(">> stateFlow $it")
//            }
//        }

        viewModel.liveData.observe(this) {
            println(">> liveData $it")
        }

        binding.btn2.setOnClickListener {
            println(">> shareFlow.subscriptionCount = ${viewModel.shareFlow.subscriptionCount.value}")
            viewModel.changeValue(1)
            viewModel.changeValue(2)
            viewModel.changeValue(3)
            viewModel.changeValue(4)
        }

        binding.btn.setOnClickListener {
            lifecycleScope.launch {
                viewModel.shareFlow.collect {
                    println(">> shareFlow2 $it")
                }
            }
        }
    }
}